// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'package:aircraft_war/bloc/game_state_cubit.dart';
import 'package:aircraft_war/commons/constants.dart';
import 'package:aircraft_war/components/logo_text.dart';
import 'package:aircraft_war/components/score_text.dart';
import 'package:aircraft_war/generated/assets.dart';
import 'package:flame/components.dart';
import 'package:flame/flame.dart';

/// Created by changlei on 2022/5/23.
///
/// 等待时显示的logo和飞机等
class GamePending extends GameStatePositionComponent {
  late final _scoreText = ScoreText();
  late final _logoText = LogoText();
  late final _aircraft = SpriteAnimationComponent(
    animation: SpriteAnimation.spriteList(
      [
        Sprite(Flame.images.fromCache(Images.me1)),
        Sprite(Flame.images.fromCache(Images.me2)),
      ],
      stepTime: 0.1,
    ),
    size: aircraftSize,
  );

  /// 布局
  void layout(Vector2 parentSize) {
    size = parentSize;
    position = Vector2.zero();

    _scoreText.layout(size);
    _logoText.layout(size);
    _aircraft.anchor = Anchor.topCenter;
    _aircraft.position = Vector2(size.x / 2, size.y * 0.25);
  }

  @override
  Future<void> onLoad() async {
    onNewState(gameRef.stateCubit.state);
  }

  @override
  void onNewState(GameState state) {
    switch (state) {
      case GameState.idle:
      case GameState.pending:
      case GameState.stopped:
        if (_logoText.parent == null) {
          _logoText.addToParent(this);
        }
        if (state == GameState.pending) {
          add(_aircraft);
        } else {
          _aircraft.removeFromParent();
        }
        if (state == GameState.stopped) {
          add(_scoreText);
        } else {
          _scoreText.removeFromParent();
        }
        break;
      case GameState.running:
      case GameState.pausing:
        _logoText.removeFromParent();
        _aircraft.removeFromParent();
        _scoreText.removeFromParent();
        break;
    }
  }
}
